package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.*;
import cn.fintecher.pangolin.common.model.TaskBoxModel;
import cn.fintecher.pangolin.common.model.UploadFile;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.BeanUtils;
import cn.fintecher.pangolin.common.utils.ExportDataToExcelUtil;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.common.utils.ZWStringUtils;
import cn.fintecher.pangolin.entity.elastic.ExportTemplate;
import cn.fintecher.pangolin.entity.elastic.ExportTemplateItem;
import cn.fintecher.pangolin.entity.elastic.PersonalContact;
import cn.fintecher.pangolin.service.dataimp.model.ExportPhoneModel;
import cn.fintecher.pangolin.service.dataimp.service.BaseService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 16:55 2019/10/19
 */

@Service("exportContactTask")
public class ExportContactTask {
    @Autowired
    private BaseService baseService;

    /**
     * 异步导出联系人信息
     */
    @Async
    public void exportFollowRecord(List<PersonalContact> contacts, ExportTemplate exportTemplate, TaskBoxModel taskBoxModel, UserModel userModel) {
        if (contacts.isEmpty()) {
            String fileId = baseService.generateTxt(Collections.singletonList("没有联系人数据导出"), Long.toString(new Date().getTime()));
            baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "联系人导出", userModel, null, ZWDateUtil.getNowDateTime(), "联系人导出");
        } else {
            try {
                List<ExportTemplateItem> items = exportTemplate.getItems();
                List<ExportPhoneModel> models = new ArrayList<>();
                for (PersonalContact contact : contacts) {
                    ExportPhoneModel exportPhoneModel = new ExportPhoneModel();
                    BeanUtils.copyPropertiesIgnoreNull(contact, exportPhoneModel);
                    processRelation(contact.getRelation(), exportPhoneModel);
                    processStatus(contact.getStatus(), exportPhoneModel);
                    processType(contact.getType(), exportPhoneModel);
                    models.add(exportPhoneModel);
                }
                List<List<String>> datas = parseContact(models, exportTemplate);
                String path = FileUtils.getTempDirectoryPath().concat(File.separator).concat("联系人导出" + System.currentTimeMillis()).concat(".xlsx");
                ExportDataToExcelUtil.exportToExcelForRecord(datas, items.stream().map(ExportTemplateItem::getTitleName).toArray(String[]::new), path);
                File file = new File(path);
                UploadFile uploadFile = baseService.uploadExcel(file);
                baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FINISHED, uploadFile.getId(), "联系人导出", userModel, null, ZWDateUtil.getNowDateTime(), "联系人导出");
            } catch (Exception e) {
                String fileId = baseService.generateTxt(Collections.singletonList("联系人导出异常"), Long.toString(new Date().getTime()));
                baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "联系人导出", userModel, null, ZWDateUtil.getNowDateTime(), "联系人导出");
            }
        }
    }

    private List<List<String>> parseContact(List<ExportPhoneModel> exportModels, ExportTemplate exportTemplate) {
        List<List<String>> dateList = new ArrayList<>();
        List<ExportTemplateItem> items = exportTemplate.getItems();
        Map<String, List<ExportPhoneModel>> map = exportModels.stream().collect(Collectors.groupingBy(ExportPhoneModel::getCaseId));
        for (Map.Entry<String, List<ExportPhoneModel>> entry : map.entrySet()) {
            List<ExportPhoneModel> list = entry.getValue();
            List<List<String>> strs = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<String> oneDate = new ArrayList<>();
                parseItems(items, list.get(i), oneDate, exportTemplate.getPublicField(), i);
                strs.add(oneDate);
            }
            dateList.addAll(strs);
        }
        return dateList;
    }

    private void parseItems(List<ExportTemplateItem> items, ExportPhoneModel exportModel, List<String> oneDate, PublicField publicField, int i) {
        if (publicField.equals(PublicField.FILL) || i == 0) { //填充
            for (ExportTemplateItem item : items) {
                String value = parseFieldsCase(exportModel, item.getAttribute());
                if (ZWStringUtils.isNotEmpty(item.getContent())) {
                    value = value + "|" + item.getContent();
                }
                oneDate.add(value);
            }
        } else if (publicField.equals(PublicField.NO_FILL) && i > 0) { //不填充
            exportModel.setCaseId(null);
            for (ExportTemplateItem item : items) {
                String value = parseFieldsCase(exportModel, item.getAttribute());
                if (ZWStringUtils.isNotEmpty(item.getContent())) {
                    value = value + "|" + item.getContent();
                }
                oneDate.add(value);
            }
        }
    }

    private String parseFieldsCase(ExportPhoneModel exportModel, String attribute) {
        Field field;
        try {
            if (Objects.nonNull(attribute)) {
                field = exportModel.getClass().getDeclaredField(attribute);
                field.setAccessible(true);
                if (Objects.nonNull(field.get(exportModel))) {
                    if (Objects.equals(field.getType().getName(), "java.util.Date")) {
                        return ZWDateUtil.fomratterDate((Date) field.get(exportModel), "yyy-MM-dd");
                    } else {
                        return field.get(exportModel).toString();
                    }
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 处理关系
     */
    private void processRelation(Relationship relationship, ExportPhoneModel exportPhoneModel) {
        if (Objects.nonNull(relationship)) {
            switch (relationship.name()) {
                case "SELF":
                    exportPhoneModel.setRelation("本人");
                    break;
                case "SPOUSE":
                    exportPhoneModel.setRelation("配偶");
                    break;
                case "PARENT":
                    exportPhoneModel.setRelation("父母");
                    break;
                case "CHILD":
                    exportPhoneModel.setRelation("家人");
                    break;
                case "RELATIVES":
                    exportPhoneModel.setRelation("亲属");
                    break;
                case "COLLEUAGUE":
                    exportPhoneModel.setRelation("同事");
                    break;
                case "FRIEND":
                    exportPhoneModel.setRelation("朋友");
                    break;
                case "OTHER":
                    exportPhoneModel.setRelation("其他");
                    break;
                case "OFFICE":
                    exportPhoneModel.setRelation("单位");
                    break;
                case "CLASSMATE":
                    exportPhoneModel.setRelation("同学");
                    break;
            }
        }
    }

    /**
     * 处理状态
     */
    private void processStatus(ContactStatus contactStatus, ExportPhoneModel exportPhoneModel) {
        if (Objects.nonNull(contactStatus)) {
            switch (contactStatus.name()) {
                case "EFFECTIVE":
                    exportPhoneModel.setStatus("有效");
                    break;
                case "INVALID":
                    exportPhoneModel.setStatus("无效");
                    break;
                case "UNKNOWN":
                    exportPhoneModel.setStatus("未知");
                    break;
            }
        }
    }

    /**
     * 处理类型
     */
    private void processType(PhoneType type, ExportPhoneModel exportPhoneModel) {
        if (Objects.nonNull(type)) {
            switch (type.name()) {
                case "MOBILE":
                    exportPhoneModel.setType("手机");
                    break;
                case "HOME_PHONE":
                    exportPhoneModel.setType("住宅电话");
                    break;
                case "OFFICE_PHONE":
                    exportPhoneModel.setType("单位电话");
                    break;
                case "UNKNOWN":
                    exportPhoneModel.setType("未知");
                    break;
            }
        }
    }
}
